package dk.itu.samd.group2.tagapastry.messages;

import java.io.IOException;
import java.util.Date;
import java.util.Vector;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import dk.itu.samd.group2.tagapastry.Index;
import dk.itu.samd.group2.tagapastry.IndexEntry;
import dk.itu.samd.group2.tagapastry.IndexRelative;
import dk.itu.samd.group2.tagapastry.Tag;
import dk.itu.samd.group2.tagapastry.TagapastryImpl;
import dk.itu.samd.group2.tagapastry.messages.forwardStrategies.MulticastReturnToOriginatorForwardStrategy;

public class SearchMsg extends IndexMsg {

	public static final short TYPE = 2;
	private static final long serialVersionUID = TYPE;

	public SearchMsg(Tag tag, NodeHandle sender) {
		super(tag, sender);
		forwardStrategy = new MulticastReturnToOriginatorForwardStrategy();
	}

	public SearchMsg(InputBuffer buf, Endpoint endpoint) throws IOException {
		super(buf, endpoint);
		forwardStrategy = new MulticastReturnToOriginatorForwardStrategy();
	}

	@Override
	public void execute(TagapastryImpl taga) {
		Index index = taga.getIndex(tag);

		if (index == null) {
			return;
		}

		if (index.bufferOrForward(this)) {
			return;
		}

		Vector<IndexEntry> results = index.getEntries();
		ResultsMsg resMsg = new ResultsMsg(tag, taga.getNodeHandle(), this.originalSender, results);
		taga.send(resMsg);
	}

	@Override
	public short getType() {
		return TYPE;
	}

	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		super.serialize(buf);
	}

	@Override
	public String toString() {
		String str = super.toString();
		return str + " }";
	}

	@Override
	public Id getRecepientId() {
		return tag.getId();
	}

	@Override
	public boolean indexCreator() {
		return false;
	}

	@Override
	public IndexMsg cloneForChild(IndexRelative child) {
		return new SearchMsg(child.getTag(), originalSender);
	}	

}
